const loginsec = document.querySelector('.login-section')
const loginlink = document.querySelector('.login-link')
const registerlink = document.querySelector('.register-link')
registerlink.addEventListener('click', () => {
    loginsec.classList.add('active')
})
loginlink.addEventListener('click', () => {
    loginsec.classList.remove('active')
})


var loginForm = document.getElementById("login-form");
loginForm.addEventListener('submit', function (event) {
    event.preventDefault();
    var usernameInput = loginForm.querySelector('input[name="username"]').value;
    var passwordInput = loginForm.querySelector('input[name="password"]').value;
    // console.log('邮箱:', usernameInput.value);
    // console.log('密码:', passwordInput.value);

    $.ajax({
        url: "/loginSubmit",
        method: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify({
            // 请求体数据
            username: usernameInput,
            password: passwordInput
        }),
        success: function (data) {
            // alert(data["reason"]);
            if (data["status"] == 0) {
                console.log(usernameInput);
                window.location.href = "http://8.141.12.238:8080/loginSuccess/" + data["userid"];
            } else {
                alert(data["reason"]);
            }
        },
    });
});

var registerForm = document.getElementById("register-form");
registerForm.addEventListener('submit', function (event) {
    event.preventDefault();
    var usernameInput = registerForm.querySelector('input[name="username"]').value;
    var useremailInput = registerForm.querySelector('input[name="useremail"]').value;
    var passwordInput = registerForm.querySelector('input[name="password"]').value;
    var confirmpasswordInput = registerForm.querySelector('input[name="confirmpassword"]').value;

    if (passwordInput !== confirmpasswordInput) {
        alert("两次输入的密码不一致");
        registerForm.querySelector('input[name="confirmpassword"]').value = "";
    } else {
        $.ajax({
            url: "/register",
            method: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify({
                // 请求体数据
                useremail: useremailInput,
                username: usernameInput,
                userpassword: passwordInput
            }),
            success: function (data) {
                if (data["status"] == 0) {
                    alert("创建新用户成功！");
                    window.location.href = "http://8.141.12.238:8080/login";
                } else {
                    alert(data["reason"]);
                    registerForm.querySelector('input[name="useremail"]').value = "";
                    registerForm.querySelector('input[name="password"]').value = "";
                    registerForm.querySelector('input[name="confirmpassword"]').value = "";
                }
            },
        });
    }
});